<template>
  <view class="topic-detail-page">
    <uni-page-header title="话题详情" :left-icon="leftIcon" @leftClick="leftClick"/>
    <view v-if="topicDetail" class="base-info-wrap">
      <div class="img-wrap">
        <u-image width="100%" height="121" radius="10" :src="getImgUrl(topicDetail.image)" />
        <view class="share-btn">
          <u-icon color="#FFF" size="20" name="share-square" />
          <button open-type="share" class="share-transparent" />
        </view>
      </div>
      <view class="topic-title">
        <view class="title">{{ topicDetail.name }}</view>
        <view class="count">{{ topicDetail.post_num }}回答</view>
      </view>
      <view class="rule-wrap">
        <view class="title">话题规则</view>
        <view class="content-wrap">
          <view
            class="content"
            :class="{'content-ellipsis': contentRows > 5}"
            :style="{ lineHeight: contentLineHeight + 'px' }"
          >
            <p>一、参与对象：每个会员ID可发帖1次</p><p>二、活动要求：</p><p>①撰写不少于30字真实使用该产品的体验感受…</p>
          </view>
          
          <view v-if="contentRows > 5" class="more-btn" @click="onViewMoreRule">
            <div class="btn-text">更多</div>
            <u-icon name="arrow-down" size="15" color="#6DD400" />
          </view>
        </view>
      </view>
      <view class="product-info" @click="goMini(topicDetail)">
        <u-image :src="getImgUrl(topicDetail.product_image)" radius="10" width="75" height="75" />
        <view class="info-wrap">
          <view class="name">{{ topicDetail.product_name }}</view>
          <view class="desc">{{ topicDetail.detail }}</view>
        </view>
      </view>
    </view>

    <capsule-tab :tab-list="tabList" @tabChange="tabChange" />
    <video-list v-if="tabActiveName === '官方专区'" :video-list="videoList" @onStar="onStar" />
    <u-empty v-if="tabActiveName === '官方专区' && videoList.length === 0" mode="data" margin-top="20" text="暂无帖子数据" />

    <WaterfallList v-if="tabActiveName === '推荐' && recommendListData.length" :outside-list="recommendListData" />
    <u-empty
      v-if="tabActiveName === '推荐' && recommendListData.length === 0"
      mode="data"
      margin-top="20"
      text="暂无帖子数据"
    />

    <WaterfallList v-if="tabActiveName === '最新发布' && newListData.length" :outside-list="newListData" />
    <u-empty
      v-if="tabActiveName === '最新发布' && newListData.length === 0"
      mode="data"
      margin-top="20"
      text="暂无帖子数据"
    />
    <fixed-entry from="2" @release="onRelease" />

    <u-popup :show="rulePopupShow" closeable :round="10" mode="bottom" @close="rulePopupShow = false">
      <view class="popup-content-wrap">
        <view class="popup-title">话题规则</view>
        <view class="rule-content" v-html="topicDetail.content" />
      </view>
    </u-popup>

    <view v-if="!isLogin" class="login-mask">
      <get-phone />
    </view>
  </view>
</template>

<script>
import {
  mapState,
  mapActions
} from 'vuex'
import {
  getImg,
  getImgs,
  execFn
} from '../utils/index'
import {
  wx_talk_subject_post_list,
  wx_talk_subject_post_like,
  wx_customer_share_prefetch,
  wx_customer_share_upd,
  wx_talk_subject_list
} from '@/api'
import CapsuleTab from '../pages/components/diary/CapsuleTab.vue'
import VideoList from '../pages/components/diary/VideoList.vue'
import WaterfallList from '../pages/components/diary/WaterfallList.vue'
import shareMixin from '../mixins/shareMixin'

export default {
  name: 'TopicDetail',
  components: {
    CapsuleTab,
    VideoList,
    WaterfallList
  },
  mixins: [shareMixin],
  data() {
    return {
      tabList: [{
        name: '官方专区',
        active: true,
        index: 1
      }, {
        name: '推荐',
        active: false,
        index: 2
      }, {
        name: '最新发布',
        active: false,
        index: 3
      }],
      rulePopupShow: false,
      curTabIndex: 1,
      pagination: {
        offset: 0,
        count: 20
      },
      videoList: [],
      newListData: [],
      recommendListData: [],
      contentLineHeight: 22,
      contentRows: 0
    }
  },
  computed: {
    ...mapState(['topicDetail', 'isLogin']),
    tabActiveName() {
      return this.tabList.find(item => item.active)?.name
    },
	leftIcon() {
	   const pages = getCurrentPages()
	   if (pages.length === 1) {
		   return 'home'
	   } else {
		   return 'arrow-left'
	   }
	}
  },
  async onLoad(options) {
    if (options.share_id && options.type == 10 && options.source_id == 21 && options.source_out_id) {
      wx_customer_share_upd({
        share_id: parseInt(options.share_id),
        type: parseInt(options.type),
        source_id: parseInt(options.source_id),
        source_out_id: parseInt(options.source_out_id)
      })

      const {
        talk_list
      } = await wx_talk_subject_list()
      const list = talk_list.map(e => {
        e.imgUrl = getImg(e.image)
        return e
      })
      const data = list.find(item => item.id == parseInt(options.source_out_id))
      if (data) {
        this.setTopicDetail(data)
      }
    }

    this.checkRuleContentLines()
    this.wx_talk_subject_post_list()
  },
  methods: {
    ...mapActions(['setTopicDetail']),
	goMini(detail) {
		if (detail.url) {
			execFn(detail.url)
		}
	},
	leftClick() {
		if (this.leftIcon === 'home') {
			wx.switchTab({
			  url: '/pages/home'
			})
		}
	},
    
    // 检测文本行数
    checkRuleContentLines() {
      const _this = this
      const query = uni.createSelectorQuery().in(this)
      query.select('.content')
        .boundingClientRect(rect => {
          const actualHeight = rect.height
          const lines = Math.ceil(actualHeight / _this.contentLineHeight)
          _this.contentRows = lines
        })
        .exec()
    },
    
    handleShareInfo() {
      const promise = new Promise((resolve, reject) => {
        wx_customer_share_prefetch({
          type: 10,
          source_id: 60
        }).then(res => {
          resolve({
            path: `pagesTopic/detail?share_id=${res.share_id}&type=10&source_id=21&source_out_id=${this.topicDetail.id}`
          })
        })
      })
      return {
        promise
      }
    },
    onViewMoreRule() {
      this.rulePopupShow = true
    },
    tabChange(obj, list) {
      this.curTabIndex = obj.index
      this.tabList = list
      this.pagination.offset = 0
      this.videoList = []
      this.recommendListData = []
      this.newListData = []
      this.wx_talk_subject_post_list()
    },
    onRelease() {
      this.$utils.navigateToPage('/pagesArticle/add')
    },
    getImgUrl(imgId) {
      return getImg(imgId)
    },
    onStar(type, index) {
      if (type == 1) {
        wx_talk_subject_post_like({
          post_id: this.videoList[index].id,
          is_enable: true
        })
        this.videoList[index].is_like = true
        this.videoList[index].like_num += 1
      }
    },
    async wx_talk_subject_post_list() {
      const type = this.curTabIndex
      const res = await wx_talk_subject_post_list({
        type,
        subject_id: this.topicDetail.id,
        ...this.pagination
      })
      if (type === 1) {
        const formatList = res.post_list.map(item => {
          if (item.video) {
            item.videoSrc = getImg(item.video)
          }

          if (item.image) {
            item.getImgs = getImgs(item.image)
          }
          return item
        })
        this.videoList = this.videoList.concat(formatList)
      }
      if (type === 2 || type === 3) {
        const formatList = res.post_list.map(e => {
          e.image = getImg(e.image)
          return e
        })
        if (type === 2) {
          this.recommendListData = this.recommendListData.concat(formatList)
        }
        if (type === 3) {
          this.newListData = this.newListData.concat(formatList)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
	.login-mask {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
	}

	.topic-detail-page {
		width: 95%;
		margin: 20rpx auto;
		position: relative;

		.base-info-wrap {
			padding: 26rpx;
			border-radius: 10rpx;
			background-color: #FFF;

			.img-wrap {
				position: relative;

				.share-btn {
					position: absolute;
					top: 10rpx;
					right: 10rpx;

					.share-transparent {
						position: absolute;
						width: 100%;
						height: 100%;
						background: transparent;
						left: 0;
						top: 0;

						&::after {
							border: none;
						}
					}
				}
			}

			.topic-title {
				margin: 20rpx 0;
				@include flex-between;

				.title {
					font-size: 28rpx;
					font-weight: bolder;
					width: 80%;
					@include text-ellipsis;
				}

				.count {
					font-size: 20rpx;
				}
			}

			.rule-wrap {
				.title {
					width: max-content;
					font-size: 24rpx;
					padding: 2rpx 22rpx;
					background-color: #FFF36D;
					border-radius: 50rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
				}

				.content-wrap {
					padding-top: 10rpx;
					display: flex;
					align-items: flex-end;
					justify-content: space-between;
					gap: 10rpx;

					.content {
						flex: 1;
						font-size: 24rpx;
            line-height: 24rpx;
            &-ellipsis{
              @include text-ellipsis(5); 
            }
					}

					.more-btn {
						@include flex-column-center;

						.btn-text {
							font-size: 26rpx;
							color: #6DD400;
						}
					}
				}
			}

			.product-info {
				@include flex-column-center;
				gap: 15rpx;
				padding-top: 20rpx;
				margin-top: 20rpx;
				border-top: 1px solid #e6e6e6;

				.info-wrap {
					.name {
						margin-bottom: 30rpx;
						@include text-ellipsis;
						font-size: 28rpx;
						font-weight: bolder;
					}

					.desc {
						font-size: 26rpx;
						color: #999;
						@include text-ellipsis(2);
					}
				}
			}
		}
	}

	.popup-content-wrap {
		height: 40vh;

		.popup-title {
			height: 80rpx;
			line-height: 100rpx;
			padding-left: 20rpx;
			font-size: 30rpx;
			flow-weight: bolder;
		}

		.rule-content {
			padding: 20rpx;
			padding-bottom: 0;
			height: calc(40vh - 80rpx);
			font-size: 26rpx;
			overflow: hidden;
			overflow-y: auto;
		}
	}
</style>
